//
//  CZUserLoginViewController.m
//  nsj_iOS
//
//  Created by apple on 2016/12/26.
//  Copyright © 2016年 GCZ. All rights reserved.
//

#import "CZUserLoginViewController.h"
#import "CZLoginView.h"
#import "CZUserPasswordLoginViewController.h"
#import "CZVerificationBtn.h"
#import "CZBaseTabBarController.h"
#import "CZNavigationController.h"
#import "CZMessionCenterViewController.h"
#import "CZUserProtocolViewController.h"
#import <UMSocialCore/UMSocialCore.h>

@interface CZUserLoginViewController () <UINavigationControllerDelegate, UITextFieldDelegate>

@end

@implementation CZUserLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.delegate = self;
    
    CZLoginView *loginView = [[[NSBundle mainBundle] loadNibNamed:@"CZLoginView" owner:nil options:nil] firstObject];
    [self.view addSubview:loginView];
    [loginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [loginView.QQLogin addTarget:self action:@selector(loginWithThirdPlatQQ) forControlEvents:(UIControlEventTouchUpInside)];
    
    [loginView.WXLogin addTarget:self action:@selector(loginWithThirdPlatWechat) forControlEvents:(UIControlEventTouchUpInside)];

    
    [loginView.passWordLoginBtn addTarget:self action:@selector(passwordLogin) forControlEvents:(UIControlEventTouchUpInside)];
    _loginView = loginView;
    
    [loginView.loginBtn addTarget:self action:@selector(loginByVerificationCode) forControlEvents:(UIControlEventTouchUpInside)];
    CZVerificationBtn *verBtn = (CZVerificationBtn *)loginView.verificationCodeBtn;
    verBtn.delgate = self;
    
    verBtn.phoneNumber = @"";
    _loginView.phoneNumberTextField.delegate = self;
    
    [self.loginView.protocolBtn addTarget:self action:@selector(protocolAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    // Do any additional setup after loading the view.
}

#pragma mark- 查看用户协议
- (void)protocolAction {
    CZUserProtocolViewController *pVC = [[CZUserProtocolViewController alloc] init];
    [self.navigationController pushViewController:pVC animated:YES];
}

#pragma mark- 密码登录
- (void)passwordLogin {
    CZUserPasswordLoginViewController *passwordLoginVC = [[CZUserPasswordLoginViewController alloc] init];
    [self.navigationController pushViewController:passwordLoginVC animated:YES];
}


#pragma mark- 使用验证码登录
- (void)loginByVerificationCode {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/user/login",APP_HOST];
    if (!_loginView.agreeBtn.selected) {
        [SVProgressHUD showErrorWithStatus:@"请阅读并同意用户协议"];
        return;
    }
    if (_loginView.phoneNumberTextField.text.length != 11) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return;
    }
    if (_loginView.phoneNumberTextField.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        return;
    }
    [SVProgressHUD showWithStatus:@"正在登录..."];
    
    NSDictionary *params;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:mRegisterId ]) {
        params = @{@"login_id" : _loginView.phoneNumberTextField.text,
                   @"code" : _loginView.verificationCodeTextField.text,
                   @"login_type" : @1,
                   @"registerid" : [[NSUserDefaults standardUserDefaults] objectForKey:mRegisterId ]};
    } else {
        params = @{@"login_id" : _loginView.phoneNumberTextField.text,
                   @"code" : _loginView.verificationCodeTextField.text,
                   @"login_type" : @1};
    }
    
    [GCZAFNetWorking POST:urlString params:params success:^(NSDictionary *response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
            [CZNsjHelper setUserInfo:self.navigationController dataDic:response];
            if (self.callBack) {
                self.callBack();
            }
        } else {
            [SVProgressHUD showErrorWithStatus:response[@"message"]];
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"登录失败"];
    }];

}
#pragma mark- 使用第三方登录
- (void)loginByQQWechatWithTpye:(NSNumber *)type userName:(NSString *)userName openID:(NSString *)openID userLogo:(NSString *)userLogo{
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/user/login",APP_HOST];
    NSDictionary *params;
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:mRegisterId]) {
        params = @{@"username" : userName,
                   @"openid" : openID,
                   @"login_type" : type,
                   @"logo" : userLogo,
                   @"registerid": [[NSUserDefaults standardUserDefaults] objectForKey:mRegisterId]};
    } else {
        params = @{@"username" : userName,
                   @"openid" : openID,
                   @"login_type" : type,
                   @"logo" : userLogo};
    }
    [GCZAFNetWorking POST:urlString params:params success:^(NSDictionary *response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
            [CZNsjHelper setUserInfo:self.navigationController dataDic:response];
            CZBaseTabBarController *rootVC = (CZBaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            CZNavigationController *homeNC = rootVC.childViewControllers[0];
            CZMessionCenterViewController *homeVC = (CZMessionCenterViewController *)homeNC.childViewControllers[0];
            [homeVC setUserIconImage];
            if (self.callBack) {
                self.callBack();
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:CZLoginSuccessNotification object:nil];
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"登录失败"];
    }];
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    CZVerificationBtn *verBtn = (CZVerificationBtn *)_loginView.verificationCodeBtn;
    verBtn.phoneNumber = textField.text;
}

#pragma mark- 第三方登录
- (void)loginWithThirdPlatQQ {
    [self getUserInfoForPlatform:(UMSocialPlatformType_QQ)];
}
- (void)loginWithThirdPlatWechat {
    [self getUserInfoForPlatform:(UMSocialPlatformType_WechatSession)];
}
- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:self completion:^(id result, NSError *error) {
        if (!result) {
            [SVProgressHUD dismiss];
        }
        UMSocialUserInfoResponse *resp = result;
        // 第三方登录数据(为空表示平台未提供)
        // 授权数据
        NSLog(@" uid: %@", resp.uid);
        NSLog(@" openid: %@", resp.openid);
        NSLog(@" accessToken: %@", resp.accessToken);
        NSLog(@" refreshToken: %@", resp.refreshToken);
        NSLog(@" expiration: %@", resp.expiration);
        
        // 用户数据
        NSLog(@" name: %@", resp.name);
        NSLog(@" iconurl: %@", resp.iconurl);
        NSLog(@" gender: %@", resp.gender);
        
        // 第三方平台SDK原始数据
        NSLog(@" originalResponse: %@", resp.originalResponse);
        
        if (platformType == UMSocialPlatformType_QQ) {
            if (resp.openid && resp.openid.length > 0 && resp.name) {
                [self loginByQQWechatWithTpye:@3 userName:resp.name openID:resp.openid userLogo:resp.iconurl];
            }
        } else {
            if (resp.openid && resp.openid.length > 0 && resp.name) {
                [self loginByQQWechatWithTpye:@4 userName:resp.name openID:resp.openid userLogo:resp.iconurl];
            }
        }
        [[NSUserDefaults standardUserDefaults] setObject:resp.iconurl forKey:User_Logo];
    }];
}


#pragma mark- 首页隐藏导航栏
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}

- (void)dealloc {
    DLog(@"%s", __func__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
